package com.lenovo.newsapp.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.lenovo.newsapp.R;
import com.lenovo.newsapp.activity.MainActivity;
import com.lenovo.newsapp.activity.NewsDetailImgActivity;
import com.lenovo.newsapp.adapter.GalleriesListAdapter;
import com.lenovo.newsapp.model.HomeNews;
import com.lenovo.newsapp.parser.InfoJSONParser;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.PreferenceUtil;
import com.lenovo.newsapp.view.MyPullToRefreshListView;
import com.lenovo.newsapp.view.MyPullToRefreshListView.OnFooterLoadListener;
import com.lenovo.newsapp.view.MyPullToRefreshListView.OnHeaderLoadListener;

public class GalleriesListFragment extends Fragment implements
		OnHeaderLoadListener, OnFooterLoadListener {

	private ProgressBar progressBar;
	private MyPullToRefreshListView listview;
	private GalleriesListAdapter myListAdapter;
	private int pageNo;
	boolean success = true;
	boolean canLoadMore = true;
	private final Handler handler = new Handler();
	private ArrayList<HomeNews> resultList = new ArrayList<HomeNews>();
	private MainActivity main;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		Const.isFrefresh=true;

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		main = (MainActivity) activity;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if(Const.isFrefresh){
			pageNo = 1;
			loadData(Const.INIT_FLAG);
			Const.isFrefresh=false;
		}
//		if(Const.GALLERIES_LIST == 0){
//			pageNo = 1;
//			loadData(Const.INIT_FLAG);
//			Const.GALLERIES_LIST = 1;
//		}



	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_galleries,
				container, false);
		listview = (MyPullToRefreshListView) rootView
				.findViewById(R.id.listview);
		progressBar = (ProgressBar) rootView
				.findViewById(R.id.loading_progressbar);
		return rootView;
	}

	private void loadMoreListView() {
		myListAdapter.appendOlder(resultList);
		listview.onFooterLoadComplete();
	}

	private void refreshListView() {
		myListAdapter.refreshData(resultList);
		listview.onHeaderLoadComplete();
	}

	@Override
	public void onFooterLoad() {

		if (null != resultList && resultList.size() > 0) {
			pageNo++;
			loadData(Const.LOAD_MORE_FLAG);
		} else {
			Toast.makeText(main, R.string.load_no_more_message,
					Toast.LENGTH_SHORT).show();
			listview.onFooterLoadComplete();
		}
	}

	private void loadData(final int flag) {
		if (flag == Const.INIT_FLAG) {
			showLoadProgressBar();
		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					resultList = InfoJSONParser.getInfoList(pageNo,PreferenceUtil.getString("username", ""),flag, main);
					canLoadMore = (resultList.size() == Const.PAGE_SIZE);
					success = true;
				} catch (Exception e) {
					success = false;
					e.printStackTrace();
				}

				handler.post(new Runnable() {

					@Override
					public void run() {
						if (success) {
							switch (flag) {
							case Const.INIT_FLAG:
								setUpListViews();
								break;
							case Const.LOAD_MORE_FLAG:
								loadMoreListView();
								break;
							case Const.REFRESH_FLAG:
								refreshListView();
							default:
								break;
							}
						} else {
							Toast.makeText(main, R.string.toast_err_download,
									Toast.LENGTH_SHORT).show();
						}

						listview.onHeaderLoadComplete();
						listview.setCanLoadFooter(canLoadMore);
						hideLoadProgressBar();
					}

				});
			}
		}).start();
	}

	@Override
	public void onHeaderLoad() {
		pageNo = 1;
		loadData(Const.REFRESH_FLAG);
	}

	protected void hideLoadProgressBar() {
		progressBar.setVisibility(View.GONE);
	}

	protected void showLoadProgressBar() {
		progressBar.setVisibility(View.VISIBLE);
	}

	private void setUpListViews() {
		Log.v(Const.DEBUG, "r.resultList.size() " + resultList.size());
		if (null != resultList && resultList.size() > 0) {
//			for (int i = 0; i < resultList.size(); i++) {
//
//				NewsApplication.addNews(resultList.get(i).getNewsId(),
//						resultList.get(i).getTitle(), resultList.get(i)
//								.getSummary(), resultList.get(i)
//								.getNewsThumbnail(), resultList.get(i)
//								.getAuthor(), resultList.get(i).getKeyword(),
//						resultList.get(i).getLastUpdateTime(), resultList
//								.get(i).getImgFrist(), resultList.get(i)
//								.getImgSecend(), resultList.get(i)
//								.getImgThird(), resultList.get(i).getImgSize(),Const.GALLERIES);
//			}
			
			myListAdapter = new GalleriesListAdapter(main, resultList);
			listview.setAdapter(myListAdapter);
			listview.setOnHeaderLoadListener(this);
			listview.setOnFooterLoadListener(this);
			listOnclicklistener listener = new listOnclicklistener();
			listview.setOnItemClickListener(listener);

		}
	}

		class listOnclicklistener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			HomeNews info = (HomeNews) listview.getItemAtPosition(position);
			
			Intent intent = new Intent(main, NewsDetailImgActivity.class);

			intent.putExtra("id", ""+info.getNewsId());
			startActivity(intent);
		}
	}
}
